<?php

namespace Application\Controller;


use Zend\View\Model\ViewModel;

use Zend\Authentication\AuthenticationService;
use Zend\Authentication\Adapter\DbTable as AuthAdapter;
use Zend\Http\PhpEnvironment\Request;

class IndexController extends \MLM\Model\Generic\Controller
{
    public function indexAction()
    {
        return new ViewModel();
    }
    
    public function loginAction(){
		$auth = new AuthenticationService();

        if ($auth->hasIdentity()) {
            $identity = $auth->getIdentity();
        }
		
        $auth->clearIdentity();
		
	$sessionManager = new \Zend\Session\SessionManager();
        $sessionManager->forgetMe();
		
		
        $view = new ViewModel();
        $view->setTerminal(true);
        return $view;
    }

    public function registerAction(){

        $view = new ViewModel();

        $db = $this->_db;

        $conn = $db->getDriver()->getConnection();

        $storage = new \MLM\Model\Member\Storage($db);
        $member = new \MLM\Model\Member($storage);
        $functModel = new \MLM\Model\Functions;
        
        $data = array();
        $request = $this->getRequest();

        if ($request->isPost()) {
            $conn->beginTransaction();
            $post = $request->getPost();
            //$form = array_merge($form, $post);

            $data = array_merge($data,  get_object_vars($post));

            /*
            echo "<pre>";
            print_r($data);
            die();
             * 
             */
          

            $view->setVariable('data', $data);


            //validate parent

            $pstat = $member->validateParent($post->upperId);

            if($pstat['code'] == 'F'){
                $conn->rollback();
                $view->setVariable('errmsg', $pstat['msg']);
                return $view;
            }


            // GENERATE New SN
            $snStorage = new \MLM\Model\Sn\Storage($db);
            $getPrefix = $snStorage->getSNConfig('SN_PREFIX');
            while($getPrefix->next()){
                    $res = $getPrefix->current();
                    $prefix = $res['str_value'];
            }


            $getLen = $snStorage->getSNConfig('SN_NUMBER_LENGTH');
            while($getLen->next()){
                    $res = $getLen->current();
                    $len = $res['int_value'];
            }


            $resSN = $snStorage->genSN($prefix, $len);
            $resArr = explode(",", $resSN);
            $memberCode = $resArr[0];
            $memberPIN = $post->pass;

          
            // assign data member
            $memberName = $post->firstName." ".$post->lastName;
            $member->name = $memberName;
            $member->parentId = $post->upperId;
            $member->sponsorId = $post->sponsorId;
            $member->matrik1Id = $post->upperId;
            $member->typeId = 2;
            $member->statusId = 1;
            $member->startDtm = $storage->now();
            $member->pos = $post->pos;
            

            $member->code = $memberCode;
            $member->pin = md5($memberPIN);

            $memberId = $member->save();

            if(!$memberId){
                $conn->rollback();
                $view->setVariable('errmsg', 'Registration failed, please try again');
                return $view;
            }
            $member->id = $memberId;

            /*
             * Account
             */

            $accStorage = new \MLM\Model\Member\Account\Storage($this->_db);
            $acc = new \MLM\Model\Member\Account($accStorage);

            $acc->accNum = $member->code;
            $acc->accName = $member->name;
            $acc->memberId = $memberId;
            $acc->amount = 0;
            $acc->amount1 = 0;
            $acc->amount3 = 0;
            $acc->amount2 = 0;
            $acc->amount4 = 0;
            $acc->status = 'OK';


            $accId = $acc->save();

            if(!$accId){
                $conn->rollback();
                $view->setVariable('errmsg', 'Registration failed, please try again');
                return $view;
            }
            // contact data
            /*
             * insert contact
             * insert member_contact
             */


            $cStorage = new \MLM\Model\Contact\Storage($this->_db);
            $contact = new \MLM\Model\Contact($cStorage);

            $contact->name = $memberName;
            $contact->ktp = $post->ktp;
            $contact->mobile = $post->mobile;
            $contact->address = $post->address;
            $contact->email = $post->email;
            $contact->city = $post->city;
            $contact->countryId = $post->country;

            $contactId = $contact->save();

            if(!$contactId){
                $conn->rollback();
                $view->setVariable('errmsg', 'Registration failed, please try again');
                return $view;
            }

            $mcStorage = new \MLM\Model\Member\Contact\Storage($this->_db);
            $memberContact = new \MLM\Model\Member\Contact($mcStorage);

            $memberContact->memberId = $memberId;
            $memberContact->contactId = $contactId;
            $memberContact->typeId = 2;
            $memberContact->startDat = $mcStorage->now();

            $mcId = $memberContact->save();

            if(!$mcId){
                $conn->rollback();
                $view->setVariable('errmsg', 'Registration failed, please try again');
                return $view;

            }

            // update sn to acctive

            $snstatus = $storage->updateSn($member->code,3);

            $req = $member->createRequest();
            if(!$req){
                $conn->rollback();
                $view->setVariable('errmsg', 'Registration failed, please try again');
                return $view;
            }
            $conn->commit();


            $mailMsg = " <a href='fx-tradepoint.co.uk'>FX Trade Point</a><br><hr>
                        Dear ans,<br>
                        Dear ans we are very thankful for joining with us,you are now a valuable consumer of our FX Trade Point beautiful family. we wish you best of luck for your future earnings.please check your login details ...

                        <br><br><br>

                        Name : ".$memberName."<br><br>
                        Customer ID : ".$member->code."<br><br>
                        Password : ".$memberPIN."<br><br>

                        <br><br><br>

                        Regards,<br>
                        FX Trade Point<br>
                        <hr><br><br>
                        <center>
                        For more information email us to info@fx-tradepoint.co.uk<br>
                        www.fx-tradepoint.co.uk
                        </center>";

            $functModel->sendMail($post->email, $mailMsg);


            return $this->redirect()->toUrl('/application/Index/register?msg=Registration success');

        }

        $request = $this->getRequest();
        $getParams = $request->getQuery();

        $keySN = array_keys($_REQUEST);
        $spId = "100";
        
        if ($keySN[0] != "msg" && $keySN[0] != "errmsg" && $keySN[0] != ""){

            $memberDetail = $storage->getMemberDetailByCode($keySN[0]);
            while($memberDetail->next()){
                    $res = $memberDetail->current();
                    $spId = $res["member_id"];                    
            }
        }

        if ($spId != ""){

            $sponsor = $storage->getSponsor($spId);
            while($sponsor->next()){
                    $res = $sponsor->current();
                    $arr = explode("#", $res["sponsor"]);

                    $arrSponsor = explode("|", $arr[0]);
                    $data["sponsorId"] = $arrSponsor[0];
                    $data["sponsorCode"] = $arrSponsor[1];
                    $data["sponsorName"] = $arrSponsor[2];

                    $arrParent = explode("|", $arr[1]);
                    $data["upperId"] = $arrParent[0];
                    $data["upperCode"] = $arrParent[1];
                    $data["upperName"] = $arrParent[2];
                    $data["pos"] = ($arrParent[3] == 1) ? 2 : 1;

            }
        }
        
   

        
        $countryList = $functModel->countryList();

        
        $view->setTerminal(true);
        $view->setVariable('countryList', $countryList);
        $view->setVariable('msg', $getParams["msg"]);
        $view->setVariable('data', $data);
        $view->setVariable('spId', $spId);
        return $view;
    }
    

    public function getsponsorAction(){
        
        $view = new ViewModel();
        $storage = new \MLM\Model\Member\Storage($this->_db);

        $getParams = $this->getRequest()->getQuery();
        $spId = $getParams["spId"];

        $sponsor = $storage->getSponsor($spId);
        while($sponsor->next()){
                $res = $sponsor->current();
                $view->setVariable('data', $res["sponsor"]);
        }
        
        $view->setTerminal(true);
        return $view;
    }

    public function sendmailAction(){ //Buat ngetes doang

            $mailMsg = " <a href='fx-tradepoint.co.uk'>FX Trade Point</a><br><hr>
                        Dear ans,<br>
                        Dear ans we are very thankful for joining with us,you are now a valuable consumer of our FX Trade Point beautiful family. we wish you best of luck for your future earnings.please check your login details ...

                        <br><br><br>

                        Name : Anton<br><br>
                        Customer ID : FXTP00020<br><br>
                        Password : 123456<br><br>

                        <br><br><br>

                        Regards,<br>
                        FX Trade Point<br>
                        <hr><br><br>
                        <center>
                        For more information email us to info@fx-tradepoint.co.uk<br>
                        www.fx-tradepoint.co.uk
                        </center>";

            $functModel = new \MLM\Model\Functions;
            $functModel->sendMail("ans_tea@yahoo.com", $mailMsg);

            $view = new ViewModel();
            $view->setTerminal(true);
            return $view;



    }

}
